package task

import (
	"crawler/data"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

func CheckUpdate() {
	CurrName := GetExeName()
	Softname := strings.ReplaceAll(CurrName, ".exe", "")
	Softname = strings.ReplaceAll(Softname, "_update", "")
	if Softname == "" {
		Softname = "crawler"
	}
	up := AutoUpdate{
		Url:      "https://gitee.com/liaodongting/crawler/raw/master/data/version.json",
		Softname: Softname,
		CurrVer:  data.Version,
		CurrName: CurrName,
	}
	fmt.Println("当前文件", up.Softname, up.CurrName)
	_  = up.Update()
	//if err != nil {
	//   tools.ShowMessage(err.Error())
	//}
}
func GetExeName() string {
	fPath, _ := exec.LookPath(os.Args[0])
	return filepath.Base(fPath)
}


//下载显示进度条
type WriteCounter struct {
	Total int64
	Count int64
}

func (wc *WriteCounter) Write(p []byte) (int, error) {
	n := len(p)
	wc.Total += int64(n)
	wc.PrintProgress()
	return n, nil
}

func (wc WriteCounter) PrintProgress() {
	//fmt.Printf("\r%s", strings.Repeat(" ", 35))
	//fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
	pregress:=int((float64(wc.Total)/float64(wc.Count))*100)
	fmt.Println(fmt.Sprintf("%v%%",pregress))
	Form1.Button2.SetCaption(fmt.Sprintf("下载中..%v%%",pregress))
}

func DownloadFile(filepath string, url string) error {
	client := http.Client{Timeout: 900 * time.Second}
	out, err := os.Create(filepath + ".tmp")
	if err != nil {
		return err
	}


	resp, err := client.Get(url)
	if err != nil {
		out.Close()
		return err
	}
	defer resp.Body.Close()
	//读取服务器返回的文件大小
	fsize, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 32)
	if err != nil {
		out.Close()
		return err
	}
	counter := &WriteCounter{Count: int64(fsize)}
	if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {
		out.Close()
		return err
	}
	out.Close()
	if err = os.Rename(filepath+".tmp", filepath); err != nil {
		return err
	}
	return nil
}
